<template>
  <div>
    <el-popover
      :popper-class="theme"
      placement="top-start"
      width="200"
      trigger="hover"
    >
      <div class="swatches">
        <span
          v-for="(item, index) in data"
          :key="index"
          class="color"
          :style="getBackground(item)"
        ></span>
      </div>
      <template #reference>
        <img
          v-if="isImgShow"
          class="color-img"
          :src="imgSrc"
          alt
        />
        <div
          v-else
          class="colorSquare"
          :style="{ backgroundColor: data[0] }"
        ></div>
      </template>
    </el-popover>
  </div>
</template>
<script>
export default {
  props: ['data', 'picName', 'componentStyle'],
  data() {
    return {
      theme: `config-popover config-popover-${window._adoPremise.uc.theme ||
        'light'}`,
      imgSrc: '',
      isImgShow: true,
    };
  },
  watch: {
    componentStyle(newVal, oldVal) {
      if (newVal && this.isImgShow) {
        this.imgSrc = new URL(`./img/${this.picName}_${newVal}.png`, import.meta.url).href;
      }
    },
  },
  created() {
    this.isImgShow = this.data.length > 1;
    if (this.isImgShow) {
      this.imgSrc = new URL(`./img/${this.picName}_${this.componentStyle}.png`, import.meta.url).href;
    }
  },
  methods: {
    getBackground(item) {
      if (Array.isArray(item) && item.length >= 2) {
        return {
          background: `linear-gradient(to right, ${item[0]}, ${item[1]})`,
        };
      } else if (item && typeof item === 'string') {
        return {
          background: `${item}`,
        };
      } else {
        return '';
      }
    },
  },
};
</script>
<style lang="less">
.config-popover {
  width: max-content !important;
  min-width: unset;
  padding: 6px 3px;
  line-height: 1;
}
.config-popover-dark {
  background: #064559;
  border-color: #064559;
}
</style>
<style lang="less" scoped>
.swatches {
  height: 13px;
  .color {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin: 0 3px;
  }
}
.colorSquare {
  width: 20px;
  height: 20px;
}
</style>
